package com.gs.synedocket.util;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class ThreadManager {
    private static volatile ThreadManager instance;
    private ThreadPoolExecutor executor;
    // cpu核心数，核心线程池的数量，执行的线程数量
    private int corePoolSize;
    // 最大的线程池数量，当缓冲队列满的时候能继续容纳的等待任务的数量
    private int maximumPoolSize;
    // 存活时间
    private int keepAliveTime;

    public ThreadManager() {
        corePoolSize = Runtime.getRuntime().availableProcessors() * 2 + 1;
        maximumPoolSize = corePoolSize;
        keepAliveTime = 1;
        executor = new ThreadPoolExecutor(
                corePoolSize,
                maximumPoolSize,
                keepAliveTime,
                TimeUnit.HOURS,
                new LinkedBlockingQueue<>()
        );
    }

    public static ThreadManager getInstance() {
        if (instance == null) {
            synchronized (ThreadManager.class) {
                if (instance == null) {
                    instance = new ThreadManager();
                }
            }
        }
        return instance;
    }

    public void execute(Runnable runnable) {
        if (runnable != null) {
            executor.execute(runnable);
        }
    }
}
